#include "Coin.h"
#include "Global.h"

USING_NS_CC;

Coin* Coin::create(cocos2d::Layer* layer, cocos2d::Vec2 pos)
{
	Coin* pRet = new Coin();

	if(pRet && pRet->init(layer, pos))
	{
		pRet->autorelease();
		return pRet;
	}
	else
	{
		delete pRet;
		pRet = NULL;
		return NULL;
	}
}

bool Coin::init(cocos2d::Layer* layer, cocos2d::Vec2 pos)
{
	if(!Node::init())
	{
		return false;
	}

	sprite = Sprite::create("Coin0.png");
	sprite->setTag(TagOfSprite::COIN_SPRITE);
	auto contentSize = sprite->getContentSize();

	sprite->setPosition(pos.x, pos.y);

	Vector<SpriteFrame*> animFrames;

	auto cacher = SpriteFrameCache::getInstance();

	for(int i = 0; i < 8; i++)
	{
		std::stringstream ss;
		ss << "coin" << i << ".png";
		auto frame = cacher->getSpriteFrameByName(ss.str());
		animFrames.pushBack(frame);
	}

	auto animation = Animation::createWithSpriteFrames(animFrames, 0.2);
	auto action = RepeatForever::create(Animate::create(animation));
	sprite->runAction(action);

	auto material = PHYSICSBODY_MATERIAL_DEFAULT;
	material.density = 0.0f;
	material.friction = 0.0f;
	material.restitution = 0.0f;

	float radius = 0.95 * contentSize.width / 2;
	auto body = PhysicsBody::createCircle(radius, material);
	body->setMass(0.0000000000000000001);
	body->setRotationEnable(false);
	body->setGravityEnable(false);
	body->setContactTestBitmask(true);
	body->setDynamic(true);

	sprite->setPhysicsBody(body);

	this->addChild(sprite, 1);

	return true;
}